package me.zhanshi123.timedworld;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitRunnable;

import java.text.MessageFormat;

public class Listeners implements Listener {
    @EventHandler
    public void onChangeWorld(PlayerChangedWorldEvent e) {
        handle(e.getPlayer());
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent e) {
        new BukkitRunnable() {
            @Override
            public void run() {
                handle(e.getPlayer());
            }
        }.runTaskLater(Main.getInstance(), 10L);
    }

    public void handle(Player player) {
        TimeLimit timeLimit = Main.getConfigManager().getData().get(player.getWorld().getName());
        if (timeLimit == null) {
            return;
        }
        if (timeLimit.isAvailable()) {
            return;
        }
        Main.getConfigManager().getCommands().forEach(cmd -> Bukkit.dispatchCommand(Bukkit.getConsoleSender(), MessageFormat.format(cmd, player.getName())));
    }
}
